﻿using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core;
using Lion.WeiXin.Tools.Log;
namespace Lion.WeiXin.Controllers
{
    [PermissionFilter]
    public class ReleaseController : Controller
    {
        DBContext db;

        public ReleaseController()
            : this(null)
        {
           
        }

        public ReleaseController(DBContext mockDB)
        {
            if (mockDB == null)
            {
                db = new DBContext();
            }
            else {
                db = mockDB;
            }
        }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string name, int currentPage, int pageSize)
        {
            //如果传入条件参数
            name = HttpUtility.UrlDecode(name);
            List<ArticleModel> list = new List<ArticleModel>();
            int totalCount = 0;
            string where = " State='待发布' ";
            if (!string.IsNullOrEmpty(name))
            {
                where = string.Format(" title like '%{0}%' and {1}", name,where);
                list = db.Articles.GetList(pageSize, currentPage,where );
                totalCount = db.Articles.GetRecordCount(where);
            }
            else
            {
                list = db.Articles.GetList(pageSize, currentPage, where);
                totalCount = db.Articles.GetRecordCount(where);
            }

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }
        /// <summary>
        /// 发布整站
        /// </summary>
        /// <returns></returns>
        public JsonResult WebSite()
        {
            try
            {
                DictionaryModel dicModel = db.Dictionarys.GetModel("102001");
                TemplateEngine engine = new TemplateEngine(dicModel.Dic_Value, Request.MapPath("~/"));

                //整站文章
                List<ArticleModel> artList = db.Articles.GetList("State='待发布'");
                engine.GenerateArticleListToHtml(artList);

                //发布栏目 10 站点下的所有栏目
                List<CategoryModel> catList = db.Categorys.GetList("Code like '10%'");  // 当前站点栏目ID=10
                engine.GenerateCategoryListToHtml(catList);

                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "发布成功!" });
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "生成失败! ");
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "发布失败!" });
            }
           

        }

        public JsonResult MoreArticles(string articleIDs)
        {
            try
            {
                DictionaryModel dicModel = db.Dictionarys.GetModel("102001");
                TemplateEngine engine = new TemplateEngine(dicModel.Dic_Value, Request.MapPath("~/"));

                //发布文章
                List<ArticleModel> artList = db.Articles.GetList(string.Format("AID in ({0})",articleIDs));

                engine.GenerateArticleListToHtml(artList);
              
                //发布栏目Code,两位为一级
                //计算需要发布的栏目：1 首页，2 当前文章所属栏目
                List<string> waitePublishCategorys = new List<string>();
                waitePublishCategorys.Add("10");  //首页
                foreach (ArticleModel item in artList)
                {
                    if (!waitePublishCategorys.Contains(item.CategoryCode))
                    { 
                         waitePublishCategorys.Add(item.CategoryCode);  
                    }
                }
                string catIds = string.Join("','",waitePublishCategorys.ToArray());
                string where = string.Format("Code in ('{0}')",catIds);
                List<CategoryModel> catList = db.Categorys.GetList(where);

                engine.GenerateCategoryListToHtml(catList);

                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "发布成功!" });
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "生成失败! ");
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "发布失败!" });
            }
        }

        public JsonResult OneArticle(int articleId)
        {
            try
            {
                DictionaryModel dicModel = db.Dictionarys.GetModel("102001");
                TemplateEngine engine = new TemplateEngine(dicModel.Dic_Value, Request.MapPath("~/"));

                ArticleModel artModel = db.Articles.GetModel(articleId);

                engine.GenerateArticleToHtml(artModel);
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "发布成功!" });
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "生成失败! ");
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "发布失败!" });
            }
        }

    }
}
